package com.abcd1234.zkPerf;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ZkLink {
    private final ZooKeeper zk;

    public ZkLink(String zkURL, Watcher clientNodeWatcher) throws IOException {
        this.zk = new ZooKeeper(zkURL, 1000000, clientNodeWatcher);
    }

    public void setNodeData(String nodePath, String data) throws KeeperException, InterruptedException {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        zk.setData(nodePath, dataBytes, -1);
    }

    public String createNode(String nodePath, String data, CreateMode createMode) throws KeeperException, InterruptedException {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        return zk.create(nodePath, dataBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
    }

    public void deleteNode(String nodePath, int version) throws KeeperException, InterruptedException {
        zk.delete(nodePath, version);
    }

    public boolean watchNode(String nodePath, boolean watch) {
        // 判断节点是否存活
        try {
            Stat nodeStat = zk.exists(nodePath, watch);
            return nodeStat != null;
        } catch (KeeperException | InterruptedException e) {
            throw new IllegalStateException("Failed to watch node: " + nodePath, e);
        }
    }

    public void close() throws InterruptedException {
        zk.close();
    }
}
